home *** CD-ROM | disk | FTP | other *** search
- {*********************************************************}
- {* AACvFrac *}
- {* Copyright (c) Julian M Bucknall 1998 *}
- {* All rights reserved. *}
- {*********************************************************}
- {* Conversion of decimal to vulgar fractions *}
- {*********************************************************}
-
- {Note: this unit is released as freeware. In other words, you are free
- to use this unit in your own applications, however I retain all
- copyright to the code. JMB}
-
- unit AACvFrac;
-
- interface
-
- const
- MaxContFracDepth = 100;
-
- const
- CvtFracEpsilon : double = 0.0001;
-
- procedure ConvertFraction(aValue : double;
- var aNumerator : longint;
- var aDenominator : longint);
-
- implementation
-
- procedure ConvertFraction(aValue : double;
- var aNumerator : longint;
- var aDenominator : longint);
- var
- Sign : integer;
- Iter : integer;
- i : integer;
- Num : double;
- Denom: double;
- Temp : double;
- ContFrac : array [0..pred(MaxContFracDepth)] of integer;
- begin
- {get the sign of the decimal fraction}
- if aValue < 0.0 then begin
- Sign := -1;
- aValue := abs(aValue);
- end
- else
- Sign := 1;
- {create the continued fraction}
- FillChar(ContFrac, sizeof(ContFrac), 0);
- ContFrac[0] := Trunc(aValue);
- Iter := 1;
- aValue := Frac(aValue);
- while (aValue >= CvtFracEpsilon) and
- (Iter < MaxContFracDepth) do begin
- aValue := 1.0 / aValue;
- ContFrac[Iter] := Trunc(aValue);
- inc(Iter);
- aValue := Frac(aValue);
- end;
- dec(Iter);
- {convert the continued fraction to a normal vulgar fraction}
- if (Iter = 0) then begin
- aNumerator := ContFrac[Iter];
- aDenominator := 1;
- end
- else begin
- Num := 1;
- Denom := ContFrac[Iter];
- for i := pred(Iter) downto 0 do begin
- Temp := Denom * ContFrac[i] + Num;
- Num := Denom;
- Denom := Temp;
- end;
- if (Denom > MaxLongint) or (Num > MaxLongint) then begin
- aNumerator := -1;
- aDenominator := -1;
- end
- else begin
- aNumerator := Sign * Trunc(Denom);
- aDenominator := Trunc(Num);
- end;
- end;
- end;
-
- end.
-